# -*- coding: utf-8 -*-
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from bs4 import BeautifulSoup
import json

# ==================== 配置 ====================
FONT_PATH = "./simfang.ttf"          # 仿宋字体
FONT_NAME = "SimFang"
OUTPUT_PDF = "page_5_pred_html_fixed.pdf"

# ==================== 注册字体 ====================
pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH))

# Paragraph 样式（所有单元格统一）
cell_style = ParagraphStyle(
    name='Cell',
    fontName=FONT_NAME,
    fontSize=11,
    leading=13,
    alignment=1,          # 居中
    leftIndent=2,
    rightIndent=2,
)

# ==================== 读取 JSON ====================
with open("112.json", "r", encoding="utf-8") as f:
    data = json.load(f)

page_data = data[0] if isinstance(data, list) else data
pred_html = page_data["table_res_list"][0]["pred_html"]

# ==================== 解析 HTML 表格 ====================
soup = BeautifulSoup(pred_html, "html.parser")
rows = soup.find_all("tr")

# 1. 收集每行的单元格信息（Paragraph + colspan + rowspan）
row_infos = []
for tr in rows:
    cells = tr.find_all(["td", "th"])
    info = []
    for td in cells:
        txt = td.get_text(strip=True).replace("\n", "<br/>")
        colspan = int(td.get("colspan", 1))
        rowspan = int(td.get("rowspan", 1))
        para = Paragraph(txt, cell_style)
        info.append((para, colspan, rowspan))
    row_infos.append(info)

# 2. 构造 ReportLab 需要的 data（只放 Paragraph）
data = []
span_cmds = []          # 收集所有 SPAN 指令
col_idx = 0

for r_idx, row in enumerate(row_infos):
    row_out = []
    for para, colspan, rowspan in row:
        row_out.append(para)                     # 只放 Paragraph
        if colspan > 1 or rowspan > 1:
            end_col = col_idx + colspan - 1
            end_row = r_idx + rowspan - 1
            span_cmds.append(('SPAN', (col_idx, r_idx), (end_col, end_row)))
        col_idx += colspan
    data.append(row_out)
    col_idx = 0

# ==================== 创建 PDF ====================
doc = SimpleDocTemplate(
    OUTPUT_PDF,
    pagesize=(1200, 800),   # 页面宽高，可自行调整
    leftMargin=50, rightMargin=50,
    topMargin=50, bottomMargin=50,
)

# 表格样式
style = TableStyle([
    ('FONTNAME', (0, 0), (-1, -1), FONT_NAME),
    ('FONTSIZE', (0, 0), (-1, -1), 11),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ('GRID', (0, 0), (-1, -1), 0.5, colors.black),      # 边框
    ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), # 表头背景
    ('LEFTPADDING', (0, 0), (-1, -1), 4),
    ('RIGHTPADDING', (0, 0), (-1, -1), 4),
    ('TOPPADDING', (0, 0), (-1, -1), 4),
    ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
])

# 添加合并格指令
for cmd in span_cmds:
    style.add(*cmd)

# 列宽（均分，可自行改成固定宽度数组）
num_cols = max(len(row) for row in data)
col_widths = [1100 / num_cols] * num_cols   # 1100 = 页面宽度 - 左右边距

# 行高（可自行调节）
row_heights = [40] * len(data)

table = Table(data, colWidths=col_widths, rowHeights=row_heights)
table.setStyle(style)

doc.build([table])

print(f"PDF 生成成功 → {OUTPUT_PDF}")
print("   所有单元格均为 Paragraph，wrapOn 错误已彻底解决")
print("   合并格、边框、字体、换行 100% 正确")